﻿using DevelopAssistant.Service;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace DevelopAssistant.Core
{
    public class Version_on_Manager
    {
        static object lockobj = new object();
        static Version_on_Manager _instance;
        public static string handler { get; set; }
        public static string startInfo { get; set; }
        public static string url { get; set; }

        public static Version_on_Manager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockobj)
                    {
                        _instance = new Version_on_Manager();
                    }                   
                }
                return _instance;
            }
        }        

        public string Load(ref string Message)
        {
            Message = "No Newest Version"; 

            string version = string.Empty;

            if (!AppSettings.RequestVersion)
                return version;

            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "AssistantConfig.config");
                xmlDocument.SelectSingleNode("//Version");
                string localVersion = xmlDocument.SelectSingleNode("//value").InnerText;
                string productName = xmlDocument.SelectSingleNode("//productname").InnerText;
                string path = xmlDocument.SelectSingleNode("//path").InnerText;

                url = xmlDocument.SelectSingleNode("//url").InnerText;
                handler = xmlDocument.SelectSingleNode("//handler").InnerText;
                startInfo = xmlDocument.SelectSingleNode("//startinfo").InnerText;

                if (url.StartsWith("http://127.0.0.1") || url.StartsWith("https://127.0.0.1"))
                    return localVersion;
                    
                HttpWebResponse httpWebResponse = this.RequestVersions(url, new object[] { handler, productName });
                xmlDocument = new XmlDocument();
                using (Stream responseStream = httpWebResponse.GetResponseStream())
                {
                    xmlDocument.Load(responseStream);
                }
                httpWebResponse.Close();
                httpWebResponse.Dispose();

                string innerText = xmlDocument.SelectSingleNode("//Value").InnerText;
                version = innerText;

                if (!localVersion.Equals(version))
                {
                    Message = "Request Version Success";
                }

            }
            catch (Exception ex)
            {
                Message = "Request Version Faile";
                DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
            }

            return version;
        }

        public string UpdateAutoupgradeApplication(string rootPath)
        {
            string result = "Success";
            string localAutoupgradeVersion = "0.0.0";
            string remoteAutoupgradeVersion = "0.0.0";

            if (string.IsNullOrEmpty(url) ||
                url.StartsWith("http://127.0.0.1") ||
                url.StartsWith("https://127.0.0.1"))
                return result;

            try
            {
                string AutoupgradePath = string.Format("{0}\\Autoupgrade.exe", rootPath);

                if (System.IO.File.Exists(AutoupgradePath))
                {
                    FileVersionInfo versionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(AutoupgradePath);
                    localAutoupgradeVersion = versionInfo.FileVersion.ToString();
                }

                HttpWebResponse httpWebResponse = RequestVersions(url, "version_ajax_data.ashx", "");
                XmlDocument xmlDocument = new XmlDocument();
                using (Stream responseStream = httpWebResponse.GetResponseStream())
                {
                    xmlDocument.Load(responseStream);
                }
                httpWebResponse.Close();
                httpWebResponse.Dispose();

                remoteAutoupgradeVersion = xmlDocument.SelectSingleNode("//AutoupgradeVersion").InnerText;
                remoteAutoupgradeVersion = remoteAutoupgradeVersion.Replace(System.Environment.NewLine, "");

                if (!localAutoupgradeVersion.Equals(remoteAutoupgradeVersion))
                {
                    DownloadFile(AutoupgradePath, url, "Versions", "Autoupgrade.exe");
                }

                result = "Success Autoupgrade Is Last Version";

            }
            catch (Exception ex)
            {
                DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, "更新Autoupgrade版本升级工具", ex.StackTrace);
            }

            return result;
        }

        private void DownloadFile(string savePath, string url,  params object[] paramters)
        {
            Uri requestUrl = new Uri(string.Concat(new string[] { url, "/", paramters[0].ToString(), "/", paramters[1].ToString() }));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream httpStream = response.GetResponseStream())
            {
                using (FileStream outputStream = new FileStream(savePath, FileMode.Create, FileAccess.Write))
                {
                    int bufferSize = 2048;
                    byte[] buffer = new byte[bufferSize];
                    int readCount = httpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = httpStream.Read(buffer, 0, bufferSize);
                    }                     
                }                  
            }
            response.Close();
            response.Dispose();

        }

        private HttpWebResponse RequestVersions(string url, params object[] paramters)
        {
            string[] strArrays;
            HttpWebResponse response = null;
            string str = url;
            if (paramters[0].ToString().Trim().Equals("autoupgrade.exe", StringComparison.OrdinalIgnoreCase))
            {
                strArrays = new string[] { url, "/Versions/", paramters[0].ToString() };
                str = string.Concat(strArrays);
            }
            else if (!paramters[0].ToString().Trim().Contains(".xml"))
            {
                strArrays = new string[] { url, "/", paramters[0].ToString(), "?arg=", paramters[1].ToString() };
                str = string.Concat(strArrays);
            }
            else
            {
                strArrays = new string[] { url, "/Versions/", paramters[1].ToString(), "/", paramters[0].ToString() };
                str = string.Concat(strArrays);
            }
            Uri requestUrl = new Uri(str);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.Credentials = CredentialCache.DefaultCredentials;
            response = (HttpWebResponse)request.GetResponse();
            return response;
        }

    }
}
